import React, { Component, PropTypes } from 'react';
import { Table, Row, Col, Spin } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import dicts from '../dicts';
import columns from './columns';
import KlineChart from '../charts/KlineChart';
import api from '../../../api';
import smileImg from '../../../assets/images/smile.png';
import sadImg from '../../../assets/images/sad.png';
import './orderDetail.less';

class OrderDetail extends Component {
	static propTypes = {
		data: PropTypes.object,
		closeOrder: PropTypes.object,
		closeOrderId: PropTypes.string,
		openOrderId: PropTypes.string,
	}
	static defaultProps = {
	}
	state = {
		marketData: undefined,
		serieName: '日K线图',
		klineType: 'day',
		loading: false,
	}
	componentDidMount() {
		this.getData(this.props);
	}
	componentWillReceiveProps(nextProps) {
		if (nextProps !== this.props && nextProps.data!=this.props.data) {
			this.getData(nextProps);
		}
	}
	getData(props) {
		this.initMarketData(props);
	}
	initMarketData = ({ data }) => {
		if(_.isEmpty(data)
		|| _.isEmpty(data.closedPositionList)) {
			return false;
		} 
		const { symbol, openTime, closeTime } = data.closedPositionList[0];
		this.setState({ loading: true });
		const startTimestamp = new Date(openTime).getTime();
		const endTimestamp = new Date(closeTime).getTime();
    let klineType = '';
    if ((endTimestamp - startTimestamp) > (24 * 3600 * 1000)) {
      klineType = 'day';
    } else if ((endTimestamp - startTimestamp) > 600 * 1000) {
      klineType = 'minute';
    } else {
      klineType = 'tick';
    }

    if (klineType === 'day') {
			const startDate = moment(startTimestamp).add(-30, 'days').format('YYYYMMDD');
			const endDate = moment(endTimestamp).add(30, 'days').format('YYYYMMDD');

			api.getSimpleDayKline({ stockCode: symbol, from: startDate, to: endDate }).then((response) => {
				this.setState({ marketData: response.data, serieName: '日K线图', klineType: 'day', loading: false });
			});
    } else if (klineType === 'minute') {
			const startTime = moment(startTimestamp).add(-20, 'minutes').format('YYYYMMDD093000');
			const endTime = moment(endTimestamp).add(20, 'minutes').format('YYYYMMDD150000');

			api.getSimpleMinKline({ stockCode: symbol, from: startTime, to: endTime }).then((response) => {
				this.setState({ marketData: response.data, serieName: '分钟K线图', klineType: 'minute', loading: false });
			});
    } else {
      const startTime = moment(startTimestamp).add(-10, 'minutes').format('YYYYMMDDHHmmss');
      const endTime = moment(endTimestamp).add(10, 'minutes').format('YYYYMMDDHHmmss');

      api.getTickKline({ stockCode: symbol, from: startTime, to: endTime }).then((response) => {
        this.setState({ marketData: response.data, serieName: '秒K线图', klineType: 'tick', loading: false });
      });
    }
	}
	render() {
		const { data, onRowClick } = this.props;
		const { marketData, serieName, klineType } = this.state;

		const closedPositionList = [];

		const markPointData = [];
		let cpOrderDetail = {};

    if (_.has(data, 'closedPositionList') && _.isArray(data.closedPositionList)) {
      data.closedPositionList.map((closePos, i) => {
        const { tradeType, buyPrice, sellPrice, openTime, closeTime, openOrderId, closeOrderId } = closePos;
        if (this.props.openOrderId === openOrderId && this.props.closeOrderId === closeOrderId) {
          cpOrderDetail = closePos;
          closedPositionList.push(closePos);
        } else {
          closedPositionList.push(closePos);
        }

        let openTimeStr;
        let closeTimeStr;
        if (klineType === 'tick') {
          openTimeStr = moment(openTime).format('YYYYMMDDHHmmss');
          closeTimeStr = moment(closeTime).format('YYYYMMDDHHmmss');
          if (_.isArray(marketData)) {
            marketData.map((aMarketData, i) => {
              if (Math.abs(openTimeStr - aMarketData[0]) < 3) {
                openTimeStr = moment(aMarketData[0], "YYYYMMDDHHmmss").format(dicts.klineDateFormat[klineType]);
              }
              if (Math.abs(closeTimeStr - aMarketData[0]) < 3) {
                closeTimeStr = moment(aMarketData[0], "YYYYMMDDHHmmss").format(dicts.klineDateFormat[klineType]);
              }
            })
          }
        } else {
          openTimeStr = moment(openTime).format(dicts.klineDateFormat[klineType]);
          closeTimeStr = moment(closeTime).format(dicts.klineDateFormat[klineType]);
        }

        if (tradeType === 'Buy') {
          markPointData.push({
            name: i + 'Buy',
            coord: [openTimeStr, buyPrice],
            value: buyPrice,
            itemStyle: {
              normal: { color: 'rgba(180, 0, 0, 0.6)' },
            },
            label: {
              normal: {
                formatter: value => '买',
              },
            },
          }, {
            name: i,
            coord: [closeTimeStr, sellPrice],
            value: sellPrice,
            itemStyle: {
              normal: { color: 'rgba(0, 180, 0, 0.6)' },
            },
            label: {
              normal: {
                formatter: value => '卖',
              },
            },
          },
          );
        } else {
          markPointData.push({
            name: i,
            coord: [openTimeStr, sellPrice],
            value: sellPrice,
            itemStyle: {
              normal: { color: 'rgba(0, 180, 0, 0.6)' },
            },
            label: {
              normal: {
                formatter: value => '卖',
              },
            },
          }, {
              name: i,
              coord: [closeTimeStr, buyPrice],
              value: buyPrice,
              itemStyle: {
                normal: { color: 'rgba(180, 0, 0, 0.6)' },
              },
              label: {
                normal: {
                  formatter: value => '买',
                },
              },
            },
          );
        }
      });
    }

		return (
			<Spin spinning={this.state.loading} >
				{!_.isUndefined(data) &&
					!_.isUndefined(data.closedPositionList) &&
					!_.isEmpty(data.closedPositionList) &&
					<div className="orderDetail">
						{data &&
							<Row>
								<Col span={8}>
									{ !_.isEmpty(data.comment) &&
										<div className="smileScore">
											<img src={data.comment.score >= 60 ? smileImg : sadImg } width='120' />
										</div>
									}
									<div className="closeOrderInfo">
										<h3>订单信息</h3>
										<p><label>单号</label><em>{data.orderId}</em></p>
										<p><label>股票</label><em>{data.symbol}</em></p>
										<p><label>类型</label><em>{dicts.closeOrderType[data.tradeType]}</em></p>
										<p><label>价格</label><em>{data.price.toFixed(2)}</em></p>
										<p><label>数量</label><em>{data.quantity}</em></p>
										<p><label>费用</label><em>{data.fee.toFixed(2)}</em></p>
										<p><label>时间</label><em>{moment(data.timestamp).format('YYYY-MM-DD HH:mm:ss')}</em></p>
                    { !_.isEmpty(data.comment) &&
                      <p><label>评语</label><em>{ data.comment.comment}</em></p>
                    }
								</div>
								</Col>
								<Col span={16}>
									{marketData && marketData.length > 0 && <KlineChart title={data.symbol} klineType={klineType} serieName={serieName} data={marketData} markPointData={markPointData} />}
								</Col>
							</Row>
						}
						<Row style={{ marginTop: 30 }}>
							<Col>
								<Table
									size="small"
									rowKey={(row) => (row.openOrderId + row.closeOrderId)}
									dataSource={closedPositionList}
									columns={columns}
									onRowClick={(record, index, e) => { onRowClick && onRowClick(record); }}
									onChange={this.handleTableChange}
                  pagination={false}
								/>
							</Col>
						</Row>
					</div>
				}
			</Spin>
		);
	}
}

export default OrderDetail;
